//  webSocet 服务器端 
// # 创建 socket
// # 监听端口
// # 监听来自客户端的链接
// # 转发消息给其他的客户端
// # 监听客户端关闭 失去链接

var ws = require("ws")
var webSocetServer = ws.Server
var port = 3300
var { stringify } = require("querystring")

var wss = new webSocetServer({ port })
console.log("this webSocket Server is running at " + port)

var count = 0
var info = "靓仔"
var onLineUser = {}

wss.on("connection", (socket) => {
    count++
    socket.name = info + count
    onLineUser[socket.name] = socket

    socket.on("message", msg => {
        boardcast(msg, socket)
    })

    socket.on("close", () => {
        boardcast("886,我下线了...", socket);
        setTimeout(() => {
            delete onLineUser[socket.name] // 通过  key 删除一个对象
        }, 5)
    })

})

function boardcast(msg, socket) {
    var time = new Date();
    var hour = time.getHours();
    var min = time.getMinutes();

    for (var key in onLineUser) {
        onLineUser[key].send(`${socket.name} (${hour}:${min}): ${msg}`); // 发送消息到客户端 
    }
}